package com.fingard.dsp.bank.directbank.hnrcb01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class HNRCB01Balance extends HNRCB01Base implements IBalance {
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        int successCount = 0;
        StringBuilder messageStr = new StringBuilder();
        try {
            while (p_req7506.readRecord()) {
                JSONObject reqJson = new JSONObject();//发给银行的json报文

                //Body
                JSONObject bodyJson = new JSONObject();
                bodyJson.put("CUSACCNO", p_req7506.readedDetail.actNum);//客户账号
                bodyJson.put("CASREMITFLG", "");//0-钞户 1-汇户 非必填
                String orggrpid=getBankConfig().getMapValueByKey("ORGGRPID", p_req7506.readedDetail.actNum);
                if(StringHelper.isNullOrEmpty(orggrpid)){
                    orggrpid="0000";
                }
                bodyJson.put("ORGGRPID",orggrpid);//集团ID 非集团账户默认值0000
                reqJson.put("body", bodyJson);

                //head
                HNRCB01Header hnrcb01Header = new HNRCB01Header();
                String customerNum = getBankConfig().getValueAsString("customerNum");//13位客户号
                String indexno = getQryTransID();//11位序列
                hnrcb01Header.reqSeqno = Format.Date8Format.format(new Date()) + customerNum + indexno;
                hnrcb01Header.trsCode = "singleAcctQuery";
                //加签字段
                //BRANCHID|USERID|USERNAME|ENTOPERID|ENTOPERNAME|REQSEQNO|CUSACCNO|ORGGRPID
                StringBuilder signaturedata = new StringBuilder();
                signaturedata.append(bankFront.org).append("|");//BRANCHID 签约机构号
                signaturedata.append(bankFront.loginName).append("|");//USERID 用户号
                signaturedata.append(bankFront.corpNo).append("|");//USERNAME 客户姓名
                signaturedata.append(bankFront.operator).append("|");//ENTOPERID 企网操作员ID
                signaturedata.append(bankFront.userName).append("|");//ENTOPERNAME 企网操作员姓名
                signaturedata.append(hnrcb01Header.reqSeqno).append("|");//REQSEQNO 流水号
                signaturedata.append(p_req7506.readedDetail.actNum).append("|");//CUSACCNO 客户账号
                signaturedata.append(orggrpid);//ORGGRPID 集团ID

                /**
                 * 发送验签报文xml
                 */
                XmlTextWriter writerXml = new XmlTextWriter();
                writeSignXml(writerXml, signaturedata.toString());
                String signDateStr[] = sendToBankBySign(writerXml.toXmlString());
                String sign = "";
                if (signDateStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(signDateStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        if (signDateStr[1].contains("signed_data")) {
                            sign = tmpBkReader.getFirstText("/msg/msg_body/signed_data");
                        }
                        if (StringHelper.isNullOrEmpty(sign)) {
                            //不用xml读取方式，用字符串截取 是因为测试的时候发现如果报错，银行前置
                            //返回报文格式是错误的缺少xml报文头开始标签
                            int errorStart = signDateStr[1].indexOf("<error_no>");
                            int errorEnd = signDateStr[1].indexOf("</error_no>");
                            String errorMsg = signDateStr[1].substring(errorStart + 10, errorEnd);
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo("加签失败,前置返回:" + errorMsg);
                            retAts.writeEnd();
                            return retAts;
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("加签失败：" + tmpSbMsg.toString());
                        retAts.writeEnd();
                        return retAts;
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("加签失败：" + signDateStr[0]);
                    retAts.writeEnd();
                    return retAts;
                }
                hnrcb01Header.signaturedata = sign;
                writeCommonHeader(hnrcb01Header, reqJson);


                String[] tmpStrRet = sendToBank(reqJson.toJSONString(), p_req7506.reqHeader.transType, p_req7506.reqHeader.transType);//可配置后置挡板请求

                if (tmpStrRet[0].length() == 0) {
                    JSONObject resultObj = JSONObject.parseObject(tmpStrRet[1]);
                    //state：返回状态，1代表成功，msg是失败提示
                    String state = resultObj.getString("STATUS");
                    String msg = resultObj.getString("MSG");
                    if (state != null && state.equals("1")) {
                        successCount++;
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = msg;
                        tmpRetDetail.actNum = p_req7506.readedDetail.actNum;
                        tmpRetDetail.actCur = convertCurToATS(resultObj.getString("CCYCD"));
                        tmpRetDetail.actArea = p_req7506.readedDetail.actArea;
                        //当前余额
                        tmpRetDetail.currBal = resultObj.getString("ACCTNOBAL");
                        //可用余额
                        tmpRetDetail.availBal = resultObj.getString("AVALBAL");
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    } else {
                        messageStr.append("账号:" + p_req7506.readedDetail.actNum + ",查询余额失败：" + msg + ";");
                    }
                } else {
                    messageStr.append("账号:" + p_req7506.readedDetail.actNum + ",查询余额失败：" + tmpStrRet[0] + ";");
                }

            }
            if (successCount > 0) {
                retAts.writeRespCode("0");
                if (messageStr.toString().length() > 0) {
                    retAts.writeRespInfo(messageStr.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(messageStr.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            WriteBankLogLn(ex);
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
